/**
 * 用户状态管理模块
 */
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import {
  User,
  UserProfile,
  UserLogin,
  UserRegister,
  UserUpdate,
  UserPasswordChange,
  UserPreferenceUpdate,
  UserState
} from '../../types/user'
import { authApi } from '../../services/api'
import { userApi } from '../../services/userApi'
import { ElMessage } from 'element-plus'

export const useUserStore = defineStore('user', () => {
  // 状态
  const currentUser = ref<User | null>(null)
  const userProfile = ref<UserProfile | null>(null)
  const token = ref<string | null>(localStorage.getItem('access_token'))
  const refreshToken = ref<string | null>(localStorage.getItem('refresh_token'))
  const loading = ref(false)

  // 计算属性
  const isLoggedIn = computed(() => !!token.value && !!currentUser.value)
  const userAvatar = computed(() => currentUser.value?.avatar || '/default-avatar.png')
  const userName = computed(() => currentUser.value?.nickname || currentUser.value?.username || '')

  // 设置token
  const setTokens = (accessToken: string, refreshTokenValue: string) => {
    token.value = accessToken
    refreshToken.value = refreshTokenValue
    localStorage.setItem('access_token', accessToken)
    localStorage.setItem('refresh_token', refreshTokenValue)
  }

  // 清除token
  const clearTokens = () => {
    token.value = null
    refreshToken.value = null
    localStorage.removeItem('access_token')
    localStorage.removeItem('refresh_token')
  }

  // 用户注册
  const register = async (userData: UserRegister) => {
    try {
      loading.value = true
      const response = await authApi.register(userData)
      if (response.code === 200) {
        return response.data
      }
      throw new Error(response.message || '注册失败')
    } catch (error: any) {
      const registerError = new Error('注册失败，请稍后重试')
      registerError.name = 'RegisterError'
      throw registerError
    } finally {
      loading.value = false
    }
  }

  // 用户登录
  const login = async (credentials: UserLogin) => {
    try {
      loading.value = true
      console.log('Sending login request with:', credentials)
      const response = await authApi.login(credentials)
      console.log('Login API response:', response)
      
      if (response.code === 200 && response.data) {
        const { access_token, refresh_token } = response.data
        setTokens(access_token, refresh_token)
        
        // 获取用户信息
        await fetchCurrentUser()
        
        return response.data
      }
      throw new Error(response.message || '登录失败')
    } catch (error: any) {
      console.error('Login error details:', error)
      console.error('Error response:', error.response?.data)
      console.error('Error status:', error.response?.status)
      
      // 如果是网络错误或服务器错误，显示具体错误信息
      if (error.response?.data?.detail) {
        const loginError = new Error(error.response.data.detail)
        loginError.name = 'LoginError'
        throw loginError
      } else if (error.response?.status === 401) {
        const loginError = new Error('用户名或密码错误')
        loginError.name = 'LoginError'
        throw loginError
      } else if (error.message && !error.message.includes('Network Error')) {
        const loginError = new Error(error.message)
        loginError.name = 'LoginError'
        throw loginError
      } else {
        const loginError = new Error('网络连接失败，请检查网络或稍后重试')
      loginError.name = 'LoginError'
      throw loginError
      }
    } finally {
      loading.value = false
    }
  }

  // 用户登出
  const logout = async () => {
    try {
      loading.value = true
      if (token.value) {
        await authApi.logout()
      }
    } catch (error) {
      console.error('Logout error:', error)
    } finally {
      currentUser.value = null
      userProfile.value = null
      clearTokens()
      loading.value = false
      
      // 清理退出登录后的相关状态
      localStorage.removeItem('currentSessionId')
      localStorage.removeItem('mainPageState')
      localStorage.removeItem('mainCurrentView')
      localStorage.removeItem('mainSelectedNovelId')
      localStorage.removeItem('mainSelectedCharacterId')
      
      ElMessage.success('已退出登录')
    }
  }

  // 获取当前用户信息
  const fetchCurrentUser = async () => {
    try {
      if (!token.value) return null
      
      const response = await authApi.getCurrentUser()
      if (response.code === 200 && response.data) {
        currentUser.value = response.data
        return response.data
      }
      throw new Error(response.message || '获取用户信息失败')
    } catch (error: any) {
      console.error('Fetch current user error:', error)
      // 如果获取用户信息失败，可能是token无效，清除登录状态
      clearTokens()
      currentUser.value = null
      throw error
    }
  }

  // 获取用户完整资料
  const fetchUserProfile = async () => {
    try {
      loading.value = true
      const profileData = await userApi.getUserProfile()
      userProfile.value = profileData
      if (currentUser.value) {
        Object.assign(currentUser.value, profileData)
      }
      return profileData
    } catch (error: any) {
      ElMessage.error({
        message: error.message || '获取用户资料失败',
        duration: 4000,
        showClose: true
      })
      throw error
    } finally {
      loading.value = false
    }
  }

  // 更新用户资料
  const updateProfile = async (profileData: UserUpdate) => {
    try {
      loading.value = true
      const updatedUser = await userApi.updateUserProfile(profileData)
      // 更新本地用户信息
      if (currentUser.value) {
        Object.assign(currentUser.value, updatedUser)
      }
      if (userProfile.value) {
        Object.assign(userProfile.value, updatedUser)
      }
      ElMessage.success('资料更新成功')
      return updatedUser
    } catch (error: any) {
      ElMessage.error({
        message: error.message || '资料更新失败',
        duration: 4000,
        showClose: true
      })
      throw error
    } finally {
      loading.value = false
    }
  }

  // 修改密码
  const changePassword = async (passwordData: UserPasswordChange) => {
    try {
      loading.value = true
      await userApi.changePassword(passwordData)
      ElMessage.success('密码修改成功')
      return true
    } catch (error: any) {
      ElMessage.error({
        message: error.message || '密码修改失败',
        duration: 4000,
        showClose: true
      })
      throw error
    } finally {
      loading.value = false
    }
  }

  // 上传头像
  const uploadAvatar = async (file: File) => {
    try {
      loading.value = true
      const avatarUrl = await userApi.uploadAvatar(file)
      // 更新本地头像URL
      if (currentUser.value) {
        currentUser.value.avatar = avatarUrl
      }
      if (userProfile.value) {
        userProfile.value.avatar = avatarUrl
      }
      ElMessage.success('头像上传成功')
      return { avatar_url: avatarUrl }
    } catch (error: any) {
      ElMessage.error(error.message || '头像上传失败')
      throw error
    } finally {
      loading.value = false
    }
  }

  // 获取用户偏好设置
  const fetchPreferences = async () => {
    try {
      const preferencesData = await userApi.getUserPreferences()
      if (userProfile.value) {
        userProfile.value.preferences = preferencesData
      }
      return preferencesData
    } catch (error: any) {
      console.error('Fetch preferences error:', error)
      throw error
    }
  }

  // 更新用户偏好设置
  const updatePreferences = async (preferencesData: UserPreferenceUpdate) => {
    try {
      loading.value = true
      await userApi.updateUserPreferences(preferencesData)
      await fetchPreferences()
      ElMessage.success('偏好设置更新成功')
      return true
    } catch (error: any) {
      ElMessage.error(error.message || '偏好设置更新失败')
      throw error
    } finally {
      loading.value = false
    }
  }

  // 初始化用户状态
  const initializeAuth = async () => {
    if (token.value) {
      try {
        await fetchCurrentUser()
      } catch (error) {
        // 如果token无效，清除登录状态
        clearTokens()
        currentUser.value = null
      }
    }
  }

  return {
    // 状态
    currentUser,
    userProfile,
    token,
    refreshToken,
    loading,
    
    // 计算属性
    isLoggedIn,
    userAvatar,
    userName,
    
    // 方法
    register,
    login,
    logout,
    fetchCurrentUser,
    fetchUserProfile,
    updateProfile,
    changePassword,
    uploadAvatar,
    fetchPreferences,
    updatePreferences,
    initializeAuth,
    setTokens,
    clearTokens
  }
}) 